// @flow
import { Modal } from 'antd'
import React from 'react'
import { connect } from 'react-redux'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './PersonalSet.css'
import UserEdit from './UserEdit'
type Props = {
  userId: number
}
type State = {
  visible: boolean,
  userData: Object
}
class PersonalSet extends React.Component {
  props: Props
  state: State
  showModal: Function
  handleCancel: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      visible: false,
      userData: {}
    }
    this.showModal = this.showModal.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
  }
  componentWillMount () {
    const { userId } = this.props
    universalFetch(`${__SERVICE_API__}sys/users/${userId}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          userData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  showModal () {
    this.setState({ visible: true })
  }
  handleCancel () {
    this.setState({ visible: false })
  }
  render () {
    const { visible, userData } = this.state
    return (
      <div>
        <div type='primary' onClick={this.showModal}>个人设置</div>
        <Modal
          visible={visible}
          title='个人设置'
          onCancel={this.handleCancel}
          footer={null}
        >
          <UserEdit data={userData} onCancel={this.handleCancel} />
        </Modal>
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    userId: state.user.userId
  }
}
const mapDispatchToProps = {}
export default connect(mapStateToProps, mapDispatchToProps)(PersonalSet)
